package com.hrhx.springboot.web;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.lionsoul.ip2region.service.DataBlock;
import org.lionsoul.ip2region.service.DbConfig;
import org.lionsoul.ip2region.service.DbMakerConfigException;
import org.lionsoul.ip2region.service.DbSearcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hrhx.springboot.jopo.ResultBean;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
 * 
 * @author duhongming
 *
 */
@Api(value="根据IP地址获取地理信息",tags="js调用")
@RestController
@RequestMapping(value = "/ipregion")
public class Ip2RegionRestController {
	
	@Value("${ip.region.db.file}")
	private String dbFile;
	
	@ApiOperation(value = "根据IP地址获取地理信息", notes = "/ipregion/query?ip=202.96.64.68")
	@ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
	@RequestMapping(value = "/query", method = RequestMethod.GET)
	public ResultBean<DataBlock> getByParentId(
			@ApiParam(required = true, name = "ip", value= "IP地址", defaultValue="202.96.64.68" ) 
			@RequestParam( value = "ip") String ip
			) 
	throws DbMakerConfigException, NoSuchMethodException, SecurityException, IllegalAccessException, 
	IllegalArgumentException, InvocationTargetException, IOException{
//		File file = ResourceUtils.getFile("classpath:ipdata/ip2region.db");
		DbConfig config = new DbConfig();
		DbSearcher searcher = new DbSearcher(config,new File(dbFile).getAbsolutePath());
		Method method = searcher.getClass().getMethod("btreeSearch", String.class);
		DataBlock dataBlock = (DataBlock) method.invoke(searcher, ip);
		searcher.close();
        return new ResultBean<DataBlock>(dataBlock);
	}
}
